<!--
 * @Author: 宋绍华
 * @Date: 2024-11-06 17:35:01
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-21 10:49:02
 * @FilePath: \sr_system_manager_ui\src\views\project\manage\publicList.vue
 * @Description: 项目管理
-->
<template>
	<div class="app-container home">
		<div>
			<SearchBar v-if='showSearch' :hideRightArea="false" :components="conditionComponents" @search="onSearch" />
			<div class="bg-#f7f8fa h-16px w-140% ml-[-20px] mt-16px"></div>
			<TableForm :auto-height="true" :data="configList" :columns="columns"
				:pageSize="20" :tableLoading="loading" :total-count="total" v-model:showSearch="showSearch"
				:show-pagination="true" :showRowSelection="true" :showToolBar="true"
				:download="(params) => { console.log('下载》', params) }" @select-rows="onSelectRows" @refresh="refreshTableData"
				@row-dblclick="(rowData) => { console.log('双击行数据》', rowData) }">
				<!-- <template #configType="{ record, rowIndex }">
					<dict-tag :options="sys_yes_no" :value="record.configType" />
				</template> -->
				<template #createTime="{ record, rowIndex }">
					<div v-if="record.approvalTime && record.conclusionTime">
						<span>{{ formateDate(record.approvalTime).format('YYYY-MM-DD') }} ~ {{
						formateDate(record.conclusionTime).format('YYYY-MM-DD') }}</span>
					</div>
					<span v-else>-</span>
				</template>
				<template #statusName="{ record }">
          <div class="flex items-center space-x-[8px]">
            <span class="h-[6px] w-[6px] rounded-[3px]"
              :style="{ backgroundColor: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }" />
            <span
              :style="{ color: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }">{{
                record.statusName }}</span>
          </div>
        </template>
				<template #default="{ record }">
					<BtnRender role="ADMIN" @update="refreshTableData(queryParams)" :record="record" :projectNature="record.projectNature" :status="record.status" />
				</template>
			</TableForm>
			<!-- 添加或修改参数配置对话框 -->
			<el-dialog :title="title" v-model="open" width="60%" append-to-body>
				<div>
					<!-- 横向不需要展示这个 -->
					<div v-if="type !== projectNatureEnum.projectNatureHorizontal" class="flex items-center">
						<el-checkbox v-model="checkFlag" label="中检提交预警" size="large" />
						<span mr-10px ml-10px inline-block>中检开始后</span>
						<el-input-number :precision="0" :disabled="!checkFlag" v-model="checkNumber" mr-10px style="width: 200px"
							placeholder="请输入" />
						<el-select :disabled="!checkFlag" v-model="checkUnit" ml-10px style="width: 200px">
							<el-option :value="1" label="天"></el-option>
							<el-option :value="2" label="月"></el-option>
							<el-option :value="3" label="年"></el-option>
						</el-select>
					</div>
					<div class="flex items-center mt-20px">
						<el-checkbox v-model="conclusionFlag" mr-10px label="结项预警" size="large" />
						<span mr-10px ml-10px inline-block>预计结项前</span>
						<el-input-number :precision="0" :disabled="!conclusionFlag" v-model="conclusionNumber" mr-10px
							style="width: 200px" placeholder="请输入" />
						<el-select :disabled="!conclusionFlag" v-model="conclusionUnit" ml-10px style="width: 200px">
							<el-option :value="1" label="天"></el-option>
							<el-option :value="2" label="月"></el-option>
							<el-option :value="3" label="年"></el-option>
						</el-select>
					</div>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" @click="submitForm">确 定</el-button>
						<el-button @click="cancel">取 消</el-button>
					</div>
				</template>
			</el-dialog>
		</div>

		<ConfirmProject v-model:visible="projectDialogVisible" v-if="projectDialogVisible" />

		<!-- 日志 -->
		<AuditRecordDrawer v-model:visible="auditRecordVisible" :project-id="curPid" v-if="auditRecordVisible" />
	</div>
</template>

<script setup name="Index" lang="ts">
import { ElMessage } from 'element-plus'
import TableForm from '@/components/TableForm/index'
import SearchBar from '@/components/SearchBar/index'
import ConfirmProject from '../components/ConfirmProject/index.vue'
import { getProjectPageApi, getDicListApi,  warningBaseCreateApi } from '@/api/project'
import formateDate from '@/utils/formateDate'
import { projectNatureEnum } from '@/utils/constEnum'
import AuditRecordDrawer from '@/components/AuditRecordDrawer/index.vue'
import { projectStatusList } from '@/utils/constText'
import { getDicListById } from '../utils'
import BtnRender from '../components/MyProject/BtnRender.vue'
import { intermediateInspectionStatusBgColorMap } from '@/utils/constText';
import { getDepartmentListReq } from '@/api/system/user'
import { DepartmentPageVO } from '@/api/system/user/type'

const route = useRoute()
const router = useRouter()
const projectDialogVisible = ref(false);
const typeList = ref([]) // 项目状态list
const projectTypeList = ref([]) // 项目分类list
const departmentList = ref([]) // 所属院系（部）list
const projectLevelList = ref([]) // 项目级别list
const auditRecordVisible = ref(false)
const selectRowList = ref<string[]>([])
const curPid = ref('') // 当前项目id

const type = computed(() => {
	return Number(route.query.projectNature)
})

watch(
	() => type.value,
	val => {
		if (val) {
			if (type.value === projectNatureEnum.projectNatureSchool) {
				nextTick(() => {
					router.currentRoute.value.meta.title = '校级项目列表';
				})
			} else if (type.value === projectNatureEnum.projectNatureHorizontal) {
				nextTick(() => {
					router.currentRoute.value.meta.title = '纵向项目列表';
				})
			} else {
				nextTick(() => {
					router.currentRoute.value.meta.title = '横向项目列表';
					console.log(router.currentRoute.value.meta, '横向项目列表');
				})
			}
		}
	},
	{
		immediate: true
	}
)

// 获取学院/部列表
const { run: getDepartmentList } = useRequest(getDepartmentListReq, {
  manual: true,
  onSuccess: (res: DepartmentPageVO[]) => {
    res?.forEach((item) => {
      item.title = item.departmentName
      item.value = item.departmentId
    })
    departmentList.value = res
  }
})

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
	manual: true,
	onSuccess: (res) => {
		// 类别
		typeList.value = getDicListById(7, res, true)
		// 项目分类
		projectTypeList.value = getDicListById(Number(route.query.projectNature) === projectNatureEnum.projectNatureHorizontal ? 6 : 5, res, true)
		// 项目级别
		projectLevelList.value = getDicListById(18, res, true)
	}
})


// 表头
const columns = ref([
	{
		title: '序号',
		minWidth: 48,
		dataIndex: 'key',
		formatter: (_row: any, _column: any, _cellValue: any, index: number) => {
			return index + 1
		}
	},
	{
		title: '项目编号',
		dataIndex: 'projectCode',
		slotName: 'projectCode',
		minWidth: 100,
	},
	{
		title: '项目名称',
		minWidth: 330,
		dataIndex: 'projectName',
		slotName: 'projectName',
		tooltip: true,
	},
	{
		title: '负责人',
		minWidth: 80,
		dataIndex: 'managerName',
		slotName: 'managerName',
		tooltip: true,
	},
	{
		title: '团队成员',
		minWidth: 120,
		dataIndex: 'teamMember',
		slotName: 'teamMember',
		tooltip: true,
	},
	{
		title: '项目分类',
		minWidth: 120,
		dataIndex: 'projectTypeName',
		slotName: 'projectTypeName',
	},
	{
		title: '项目类别',
		minWidth: 120,
		dataIndex: 'projectCategoryName',
		slotName: 'projectCategoryName',
		tooltip: true,
	},
	{
		title: '所属院系（部）',
		minWidth: 140,
		dataIndex: 'departmentName',
		slotName: 'departmentName',
		tooltip: true,
	},
	{
		title: '起止时间',
		minWidth: 170,
		dataIndex: 'createTime',
		slotName: 'createTime',
		tooltip: true,
	},
	{
		title: '项目经费',
		minWidth: 80,
		dataIndex: 'projectFunding',
		slotName: 'projectFunding',
		tooltip: true,
	},
	{
		title: '项目级别',
		minWidth: 110,
		dataIndex: 'projectLevelName',
		slotName: 'projectLevelName',
		tooltip: true,
	},
	{
		title: '项目状态',
		minWidth: 110,
		dataIndex: 'statusName',
		slotName: 'statusName',
		tooltip: true,
	},
	{
		minWidth: 200,
		title: '操作',
		dataIndex: 'default',
		slotName: 'default',
	}
])


// 搜索条件组件配置数据
const conditionComponents = ref([
	{
		type: 1,
		key: 'projectType',
		value: '单选框',
		placeholder: '项目分类',
		config: {
			options: projectTypeList
		}
	},
	{
		type: 1,
		key: 'projectCategory',
		value: '',
		placeholder: '项目类别',
		config: {
			options: typeList
		}
	},
	{
		type: 1,
		key: 'department',
		value: '',
		placeholder: '所属院系（部）',
		config: {
			options: departmentList
		}
	},
	{
		type: 1,
		key: 'projectLevel',
		value: '',
		placeholder: '项目级别',
		config: {
			options: projectLevelList
		}
	},
	{
		type: 2,
		key: 'createTime',
		value: '',
		width: 280,
		placeholder: '起止时间',
		config: {
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			}
		}
	},
	{
		type: 1,
		key: 'status',
		value: '单选框',
		placeholder: '项目状态',
		config: {
			options: projectStatusList,
			multiple: true
		}
	},
	{
		type: 0,
		value: '',
		key: 'managerName',
		placeholder: '请输入负责人',
	},
	{
		type: 0,
		value: '',
		key: 'projectName',
		placeholder: '请输入项目名称',
	},
])
const { proxy } = getCurrentInstance();
// const { sys_yes_no } = proxy.useDict("sys_yes_no");

const configList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const checkFlag = ref(true) // 中检提交预警
const checkNumber = ref(1) // 中检开始后
const checkUnit = ref(1) // 中检开始后
const conclusionFlag = ref(true) // 结项预警
const conclusionNumber = ref(1) // 结项预警前
const conclusionUnit = ref(1) // 

// 项目列表
const { run: getList } = useRequest(getProjectPageApi, {
	manual: true,
	onSuccess: (response) => {
		configList.value = response.content
		total.value = response.totalElements;
		loading.value = false;
	}
})

// 项目预警设置
const { run: warningBaseCreate } = useRequest(warningBaseCreateApi, {
	manual: true,
	onSuccess: (response) => {
		if (response.code === 200) {
			ElMessage({
				message: '设置成功',
				type: 'success',
			})
		}
	}
})

const data = reactive({
	form: {},
	queryParams: {
		page: 1,
		size: 20,
		noticeId: route.query.noticeId
	},
	rules: {
		configName: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
		configKey: [{ required: true, message: "参数键名不能为空", trigger: "blur" }],
		configValue: [{ required: true, message: "参数键值不能为空", trigger: "blur" }]
	}
});

const { queryParams, form } = toRefs(data);

const refreshTableData = (params) => {
	console.log('刷新参数》', params)
	loading.value = true
	queryParams.value.page = params.page;
	getList({ ...queryParams.value, });
	setTimeout(() => {
		loading.value = false
	}, 1000)
}

const onSelectRows = (ids) => {
	console.log('选中的ids》', ids)
	selectRowList.value = ids
}

/** 取消按钮 */
function cancel() {
	open.value = false;
	reset();
}

/** 表单重置 */
function reset() {
	form.value = {
		configId: undefined,
		configName: undefined,
		configKey: undefined,
		configValue: undefined,
		configType: "Y",
		remark: undefined
	};
	proxy.resetForm("configRef");
}

/** 提交按钮 */
function submitForm() {
	if (selectRowList.value.length === 0) {
		ElMessage.error('请选择需要发布的通知')
		return
	}
	if (conclusionFlag.value && conclusionNumber.value === '') {
		return ElMessage.error('请填写完整')
	}

	let params = {
		conclusionFlag: conclusionFlag.value,
		conclusionNumber: conclusionFlag.value ? conclusionNumber.value : undefined,
		conclusionUnit: conclusionFlag.value ? conclusionUnit.value : undefined
	}
	if (type.value !== projectNatureEnum.projectNatureHorizontal) {
		if (checkFlag.value && checkNumber.value === '') {
			return ElMessage.error('请填写完整')
		}
		params = {
			...params,
			checkFlag: checkFlag.value,
			checkNumber: checkFlag.value ? checkNumber.value : undefined,
			checkUnit: checkFlag.value ? checkUnit.value : undefined,
		}
	}
	warningBaseCreate({ ...params, projectNature: type.value })
}

// 搜索
function onSearch(params) {
	console.log('搜索参数》', params)
	const [approvalTime, conclusionTime] = params?.createTime || []
	console.log(queryParams, 'queryParams');
	queryParams.value = Object.assign(queryParams.value, params)
	getList({ ...params, ...queryParams.value, createTime: undefined, approvalTime, conclusionTime })
}

getList({ ...queryParams.value });
getDicList({})
getDepartmentList()

</script>

<style scoped lang="scss">
.home {
	blockquote {
		padding: 10px 20px;
		margin: 0 0 20px;
		font-size: 17.5px;
		border-left: 5px solid #eee;
	}

	hr {
		margin-top: 20px;
		margin-bottom: 20px;
		border: 0;
		border-top: 1px solid #eee;
	}

	.col-item {
		margin-bottom: 20px;
	}

	ul {
		padding: 0;
		margin: 0;
	}

	font-family: "open sans",
	"Helvetica Neue",
	Helvetica,
	Arial,
	sans-serif;
	font-size: 13px;
	color: #676a6c;
	overflow-x: hidden;

	ul {
		list-style-type: none;
	}

	h4 {
		margin-top: 0px;
	}

	h2 {
		margin-top: 10px;
		font-size: 26px;
		font-weight: 100;
	}

	p {
		margin-top: 10px;

		b {
			font-weight: 700;
		}
	}

	.update-log {
		ol {
			display: block;
			list-style-type: decimal;
			margin-block-start: 1em;
			margin-block-end: 1em;
			margin-inline-start: 0;
			margin-inline-end: 0;
			padding-inline-start: 40px;
		}
	}
}
</style>